package org.zhs.config;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;
import org.zhs.constants.SessionKeyConstants;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
//这个接口是用于实现一些国际化操作的,重写它来达到自定义的效果
public class MyLocaleResolver implements LocaleResolver {
    @Override
    public Locale resolveLocale(HttpServletRequest request) {
//        获取html中携带的语言参数,解析语言_解析语言所在国家
        String language = request.getParameter("l");
        //只保存不为空的情况下的语言环境,为空时是默认的语言环境不做保存
        if( !isLanguageEmpty(language) ){
            String[] s = language.split("_");
            String languageTag =  s[0]+"_"+s[1];
            request.getSession().setAttribute(SessionKeyConstants.LANGUAGE_KEY,languageTag);
        }
//        重写了之后,以后所有的请求都会通过这个方法检查语言参数,所以先设置一个默认的
        Locale aDefault = Locale.getDefault();
//        判断language是否为空
        if (!isLanguageEmpty(language)){
            String[] s = language.split("_");
            aDefault = new Locale(s[0],s[1]);
        }
//        之后还要去自定义MVC类中实现
        return aDefault;
    }

    private boolean isLanguageEmpty(String language){
        return StringUtils.isEmpty(language) || "null".equals(language);
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
